package com.hdl.school.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.PlanTask;
import com.hdl.school.utils.BroadcastAction;
import com.hdl.school.utils.TimeUtil;
import com.leectrl.utils.Bus;

/**
 * Created by Admin on 2016/11/3.
 */
public class PlayerService extends Service {
    private MediaPlayer player = null;
    private AudioBroadcastReceiver receiver;
    private PlanTask planTask;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (planTask != null && planTask.isLoop()) {
                    start();
                }else{
                    MyApplication.getAppContext().isAudioPlaying=false;
                    Bus.getInstance().emit("scene_event","voice_finish");
                }
            }
        });
        player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (planTask != null) {
                    start();
                }
                return false;
            }
        });
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (planTask != null) {
                    long duration = mp.getDuration();
                    long currentPosition = 0;
                    if (duration > 0) {
                        currentPosition = (TimeUtil.currentStap() - planTask.getTime()) % duration;
                    }
                    if (currentPosition > 0) {
                        mp.seekTo((int) currentPosition);
                    }
                    if (duration > 0 && TimeUtil.currentStap() - planTask.getTime() >= duration && (!planTask.isLoop())) {
                        player.stop();

                    } else {
                        player.start();
                    }
                }

            }

        });
        receiver = new AudioBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastAction.ACTION_MEDIA_ENVENT);
        registerReceiver(receiver, filter);
    }


    public void start() {
        try {
            if (planTask != null) {
                player.reset(); //重置多媒体
                player.setDataSource(planTask.getFileUrl());//为多媒体对象设置播放路径
                player.setVolume(1,1);
                player.prepare();//准备播放
                MyApplication.getAppContext().isAudioPlaying=true;
                Bus.getInstance().emit("scene_event","voice_start");
            }

        } catch (Exception e) {
            Log.v("MusicService", e.getMessage());
        }
    }


    class AudioBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String mAction = intent.getStringExtra("action");
            int mediaType = intent.getIntExtra("media_type", 0);
            if (BroadcastAction.ACTION_MEDIA_ENVENT.equals(action)) {
                if (mAction.equals("stopMusic") || mAction.equals("stopall")) {
                    if (player.isPlaying()) {
                        player.stop();//停止音频的播放
                    }
                    MyApplication.getAppContext().isAudioPlaying=false;
                } else if (mAction.equals("play") && mediaType == 1){
                    planTask = JSONObject.parseObject(intent.getStringExtra("task"), PlanTask.class);
                    start();
                }
            }
        }
    }
}
